<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 300px;" class="filter-item" placeholder="名称" v-model="whereQuery.name"></el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="155" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createdTime | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200" header-align="center" label='名称' show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="140px" header-align="center" align="center" label='编号'>
        <template slot-scope="scope">
          <span>{{scope.row.number}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="80px" header-align="center" align="center" label='状态'>
        <template slot-scope="scope">
          <span>{{scope.row.status | statusFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="80px" header-align="center" align="center" label='是否展示' show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.type | typeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="140px" header-align="center" align="center" label='mac'>
        <template slot-scope="scope">
          <span>{{scope.row.mac}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="300" align="left" header-align="center" label="校验码">
        <template slot-scope="scope">
          <span style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;">{{scope.row.key}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="200px" header-align="center" label='说明' show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.info}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="225" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.type === 2" size="mini" type="success" @click="handleType(scope.row, 1)">展　示</el-button>
          <el-button v-else size="mini" type="warning" @click="handleType(scope.row, 2)">不展示</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 500px; margin-left:50px;'>
        <el-form-item label="编号" prop="number3">
          <el-col :span="13">
            <el-cascader v-model="temp.number1" :options="numberOptions" expand-trigger="hover"></el-cascader>
          </el-col>
          <el-col :span="1">&nbsp;
          </el-col>
          <el-col :span="6">
            <el-input v-model="temp.number2" :maxlength="5" clearable></el-input>
          </el-col>
          <el-col :span="1">&nbsp;
          </el-col>
          <el-col :span="3">
            <el-input v-model="temp.number3" :readonly="true"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="mac" prop="mac">
          <el-input v-model="temp.mac"></el-input>
        </el-form-item>
        <el-form-item label="说明">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 6}" placeholder="请输入内容" v-model="temp.info">
        </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { saveDevice, listDevice, deleteDevice } from '@/api/monitor'
  import waves from '@/directive/waves'
  import { MessageBox } from 'element-ui'

  export default {
    name: 'device',
    directives: {
      waves
    },
    data() {
      const validateNumber = (rule, value, callback) => {
        this.handleNumber()
        if (value === undefined) {
          callback(new Error('设备编号错误'))
        } else {
          callback()
        }
      }
      return {
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 0,
          size: 10,
          name: undefined
        },
        whereQuery: {
          name: undefined
        },
        temp: {
          id: undefined,
          name: undefined,
          status: undefined,
          key: undefined,
          createdTime: undefined,
          mac: undefined,
          info: undefined,
          number: undefined,
          number1: undefined,
          number2: undefined,
          number3: undefined
        },
        numberOptions: [
          {
            value: '10',
            label: 'Shield',
            children: [
              {
                value: '13',
                label: 'shield某个产地',
                children: [
                  {
                    value: '001',
                    label: '第001批'
                  }, {
                    value: '002',
                    label: '第002批'
                  }
                ]
              }
            ]
          }, {
            value: '99',
            label: '测试设备',
            children: [
              {
                value: '01',
                label: '北京',
                children: [
                  {
                    value: '001',
                    label: '第001批'
                  }, {
                    value: '002',
                    label: '第002批'
                  }
                ]
              }
            ]
          }
        ],
        statusOptions: [1, 2, 3, 4, 5, 6],
        power: [7, 9, 11, 5, 8, 4, 6, 3, 7, 9, 11, 5],
        dialogFormVisible: false,
        jsonVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          number3: [{ required: true, validator: validateNumber, trigger: 'change' }],
          type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
          mac: [{ required: true, message: 'mac不能为空', trigger: 'change' }]
        }
      }
    },
    filters: {
      json: (value) => { return JSON.stringify(value, null, 2) },
      typeFilter(type) {
        const types = ['展　示', '不展示']
        return type > 0 ? types[type - 1] : '展　示'
      },
      statusFilter(type) {
        const types = ['待发出', '已发出', '已激活', '已回收', '已报废', '其他']
        return type > 0 ? types[type - 1] : ''
      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        this.listQuery.name = this.whereQuery.name
        listDevice(this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 0
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val - 1
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: undefined,
          status: undefined,
          key: undefined,
          createdTime: undefined,
          mac: undefined,
          info: undefined,
          number: undefined,
          number1: undefined,
          number2: undefined,
          number3: undefined
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData['number'] = this.temp.number1.join('') + this.temp.number2 + this.temp.number3
            tempData['number1'] = undefined
            tempData['number2'] = undefined
            tempData['number3'] = undefined
            saveDevice(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleNumber() {
        if (this.temp.number2 !== undefined && this.temp.number2.length === 5 && this.temp.number1 !== undefined) {
          var nums = []
          const num1 = this.temp.number1.join('')
          for (var i = 0; i < num1.length; i++) {
            var n = parseInt(num1.charAt(i))
            nums.push(n)
          }
          for (i = 0; i < this.temp.number2.length; i++) {
            n = parseInt(this.temp.number2.charAt(i))
            nums.push(n)
          }
          var sums = 0
          for (i = 0; i < nums.length; i++) {
            sums += nums[i] * this.power[i]
          }
          switch (sums % 10) {
            case 9:
              this.temp.number3 = '3'
              break
            case 8:
              this.temp.number3 = '4'
              break
            case 7:
              this.temp.number3 = '5'
              break
            case 6:
              this.temp.number3 = '6'
              break
            case 5:
              this.temp.number3 = '7'
              break
            case 4:
              this.temp.number3 = '8'
              break
            case 3:
              this.temp.number3 = '9'
              break
            case 2:
              this.temp.number3 = '2'
              break
            case 1:
              this.temp.number3 = '0'
              break
            case 0:
              this.temp.number3 = '1'
              break
          }
        } else {
          this.temp.number3 = undefined
        }
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (this.temp.number !== undefined && this.temp.number.length === 13) {
          const head = [this.temp.number.substring(0, 2), this.temp.number.substring(2, 4), this.temp.number.substring(4, 7)]
          this.temp['number1'] = head
          this.temp['number2'] = this.temp.number.substring(7, 12)
          this.temp['number3'] = this.temp.number.substring(12, 13)
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData['number'] = this.temp.number1.join('') + this.temp.number2 + this.temp.number3
            tempData['number1'] = undefined
            tempData['number2'] = undefined
            tempData['number3'] = undefined
            saveDevice(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          MessageBox.confirm('别怪我没有提醒你，删了就没有，不能恢复!!!!!!', '确定删除', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteDevice(row.id).then(response => {
              if (response.status === 200) {
                this.$notify({
                  title: '成功',
                  message: '删除成功',
                  type: 'success',
                  duration: 2000
                })
                const index = this.list.indexOf(row)
                this.list.splice(index, 1)
              } else {
                this.$notify({
                  title: '失败',
                  message: response.data.message,
                  type: 'info',
                  duration: 2000
                })
              }
            })
          })
        })
      },
      handleType(row, value) {
        const data = {
          id: row.id,
          type: value
        }
        saveDevice(data).then(response => {
          if (response.status === 200) {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message,
              type: 'info',
              duration: 2000
            })
          }
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      }
    }
  }
</script>
